import {
  Component,
  OnInit,
  NgZone,
  ChangeDetectorRef,
  Input,
  Output,
  EventEmitter,
  ViewChild,
  TemplateRef,
} from '@angular/core';
import { ControlContainer, FormGroup, FormControl, FormGroupName } from '@angular/forms';
import { MatDialog } from '@angular/material';
import { ToasterService } from '../../services/toaster.service';

@Component({
  selector: 'm-script-input',
  templateUrl: './script-input.component.html',
  styleUrls: ['./script-input.component.scss'],
})
export class ScriptInputComponent implements OnInit {
  @Input() btnText = '上传';
  @Input() viewBtnText = '查看';
  @Input() orther = '';
  @Input() nameSuffixNot; //上传文件错误提示语
  @Output() select = new EventEmitter<UploadAttach>();
  @Output() clear = new EventEmitter<UploadAttach>();
  @Output() view = new EventEmitter<UploadAttach>();
  @Output() downTemp = new EventEmitter<UploadAttach>();
  @ViewChild('viewRef') viewRef: TemplateRef<any>;

  Obj=window['Object']

  constructor(
    private cd: ChangeDetectorRef,
    public dialog: MatDialog,
    private controlContainer: ControlContainer,
    private toaster: ToasterService,
  ) { }

  group = new FormGroup({
    name: new FormControl(),
    content: new FormControl(),
    blob: new FormControl(false),
  });

  ngOnInit() {
    if (this.controlContainer instanceof FormGroupName) {
      this.group = this.controlContainer.control;
    }
  }
  transformObjToString(s:any){
    if(typeof(s)=='object' && s!=null && Object.keys(s).length==0){
      return ''
    }else{
      return s;
    }
  }

  onClear() {
    if (this.clear.observers.length) {
      this.clear.emit();
    }
    this.select.emit({ name: '', content: '', file: null, contentText: '' });
    this.group.patchValue({ name: '', content: '', upload_at: null });
  }
  //下载模板
  downTempTo() {
    this.downTemp.emit();
  }
  onView() {
    if (this.view.observers.length) {
      this.view.emit(this.group.value);
    } else {
      this.dialog.open(this.viewRef);
    }
  }

  async selectFile() {
    // 创建文件输入元素，选择文件
    const input = document.createElement('input');
    input.type = 'file';
    input.click();
    await new Promise((resolve) => (input.onchange = resolve));
    const name = input.files[0].name;
    if (!this.validateSuffix(name)) {
      this.toaster.warn(`只能上传后缀名是 ${this.nameSuffixNot} 的文件`);
      return;
    }
    if (!input.files.length) {
      return;
    }
    // 读取文件
    const content = URL.createObjectURL(input.files[0]);
    this.group.patchValue({ name, content });
    // 触发检测
    this.cd.markForCheck();
    const reader: FileReader = new FileReader()
    reader.onload = (event: any) => {
      const c: any = event.target.result;
      this.select.emit({ name, content, file: input.files[0], contentText: c });
      this.group.patchValue({ name, content });
    } // desired file content
    reader.readAsText(input.files[0]);
  }

  validateSuffix(name) {

    //null表示允许任意类型的扩展名
    if (this.nameSuffixNot === null) {
      return true;
    }
    var index = name.lastIndexOf('.');
    var fileType = name.substring(index + 1, name.length);
    if (Array.isArray(this.nameSuffixNot)) {
      return this.nameSuffixNot.some((suffix) => fileType === suffix);
    } else {
      return fileType === this.nameSuffixNot || !this.nameSuffixNot;
    }
  }
}

interface UploadAttach {
  name: string;
  content: String;
  file: object,
  contentText: string | ArrayBuffer
}
